﻿using System.Collections.Concurrent;

namespace IOP.Pulsar.Abstractions
{
    /// <summary>
    /// 上下文池
    /// </summary>
    /// <typeparam name="TContext"></typeparam>
    public class ContextPool<TContext> : IContextPool<TContext>
        where TContext : class, new()
    {
        /// <summary>
        /// 上下文队列
        /// </summary>
        private readonly ConcurrentQueue<TContext> _ContextQueue = new ConcurrentQueue<TContext>();

        /// <summary>
        /// 获取上下文
        /// </summary>
        /// <returns></returns>
        public TContext GetContext()
        {
            while (!_ContextQueue.IsEmpty)
            {
                if (_ContextQueue.TryDequeue(out TContext context)) 
                    return context;
            }
            return new TContext();
        }

        /// <summary>
        /// 回收上下文
        /// </summary>
        /// <param name="context"></param>
        public void Recovery(TContext context)
        {
            _ContextQueue.Enqueue(context);
        }
    }
}
